const express = require('express');
const LinkMan = require('../model/linkman');

const router = express.Router();

const Linkman=require('../model/linkman')

// 添加乘车人
router.post('/add', async (req, res) => {
    const { realName, idNumber, phone} = req.body;
    
    const uid = 1;


    // 数据过滤
    if (!realName) return res.send({ success: false, info: '请填写真实姓名' });
    if (!idNumber) return res.send({ success: false, info: '请填写正确的身份证号码' });
    if (/^1(3456789)\d{9}$/.test(phone)) return res.send({ success: false, info: '请填写正确的手机号码' });
    
    //添加入库
    try {
        const one = await Linkman.findOne({ phone });//找不到的话返回null
        if (one) return res.send({ success: false, info: '当前手机号码已经被占用' });
        
        await Linkman.create({
            realName,
            idNumber,
            phone,
            uid
        })
        res.send({success:true,info:'添加成功'})
    } catch (error) {
        res.send({ success: false, info: '未知错误,请与网站管理员联系' })
    } 
})

// 修改乘车人信息
router.post('/edit', async (req, res) => {
    const { phone,LinkmanId  } = req.body;

    if(!LinkmanId) return res.send({ success: false, info: '请填写必要参数' })

    if (/^1(3456789)\d{9}$/.test(phone)) return res.send({ success: false, info: '请填正确的手机号码' });

    let updateDate = { phone };
       
    //执行修改
    try {
        await Linkman.findOneAndUpdate({LinkmanId,
        },updateDate)
        res.send({success:true,info:'修改成功'})
    } catch (error) {
        res.send({ success: false, info: '未知错误,请与网站管理员联系' })
    }
})

// 获取全部乘车人信息
router.post('/getAll', async (req, res) => {
    const uid = 1;
   
    //执行修改
    try {
        const linkmans = await LinkMan.find({
           uid
       })
        res.send({success:true,info:'查询成功',data:linkmans})
    } catch (error) {
        res.send({ success: false, info: '查询失败' })
    }
})

module.exports = router;